﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

using System.ServiceModel.DomainServices.Client;
using LEEAAttendanceControl.Web;

namespace LEEAAttendanceControl.Views
{
    public partial class Exceptions : Page
    {
        public Exceptions()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            App myApp = (App)Application.Current;

            myApp.ClearEvents();

            myApp.AddEvent += NewExceptionHandler;
            myApp.EditEvent += EditExceptionHandler;
            myApp.DeleteEvent += DeleteExceptionHandler;
        }

        private void ExceptionsDatasource_LoadingData(object sender, LoadingDataEventArgs e)
        {
            e.LoadBehavior = LoadBehavior.RefreshCurrent;
        }

        public void NewExceptionHandler(object sender, EventArgs e)
        {
            ExceptionEdit newException = new ExceptionEdit("New Exception");

            newException.LoadData(-1);
            newException.Closed += WindowClosed;

            newException.Show();
        }

        public void EditExceptionHandler(object sender, EventArgs e)
        {
            if (ExceptionsGrid.SelectedItem != null)
            {
                Exeption selectedException = ExceptionsGrid.SelectedItem as Exeption;

                ExceptionEdit editException = new ExceptionEdit("Edit Exception");

                editException.LoadData(selectedException.ID);
                editException.Closed += WindowClosed;

                editException.Show();
            }
        }

        public void DeleteExceptionHandler(object sender, EventArgs e)
        {
            if (ExceptionsGrid.SelectedItem != null)
            {
                MessageDisplay message = new MessageDisplay(ApplicationStrings.DeleteMessage
                    , ApplicationStrings.Delete, "Ask");

                message.Closed += (s, ee) =>
                {
                    ExceptionsDatasource.DataView.Remove(ExceptionsGrid.SelectedItem);

                    ExceptionsDatasource.SubmitChanges();
                };

                message.Show();
            }
        }

        private void WindowClosed(object sender, EventArgs e)
        {
            ExceptionsDatasource.Load();
        }
    }
}
